
/*******************************************************************************
 * The code below this comment is integral part of the project "Jelliphy".
 * 
 * "Jelliphy" is a project created by: 
 * Dispage - Patrizio Gelosi
 * Via A. De Gasperi 91 
 * P. Potenza Picena (MC) - Italy
 * 
 * (Hereby referred to as "DISPAGE")
 * 
 * Copyright (c) 2011 DISPAGE.
 * 
 * @Released on: 02-06-2011
 * @Version: 1.0.00
 * @Build: 1109
 * @Site: http://www.dispage.com
 * @Contacts: http://www.dispage.com/contacts
 * 
 * The contents of this file are released under the GNU General Public License
 * version 3 as published by the Free Software Foundation that can be found at
 * the address "http://opensource.org/licenses/gpl-3.0.html". If the license
 * cannot be found, write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 * You may not use the present file except in compliance with the License.
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * Dispage" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by Dispage".
 * 
 ******************************************************************************/

var MGP = new function () {

	var that = this,

		matchValue, scriptName, startMatchValue, syntMatch, oldLastCalled, 
			
		cursorDelay = 100,
		dblClickDelay = 500,
		oldPageX, oldPageY,
		changingCursor = 0,
		clickTime,
		mainStatus = 'loading',

		$window,

		propShown = {
			text : false,
			bkground : false,
			layout : false,
			boxmodel : false,
			typespec : false,
			other : false
		},


		
		getWindowDim = function () {

			return {width: $window.width(), height: $window.height()};
		},
		
		adaptStyle = function () {

			var safari = '';

			if (JlQ.browser.webkit || JlQ.browser.safari) {
				if (JlQ.browser.safari) {
					safari = '.JLui-dialog {z-index: 2000100;} .JLui-widget-overlay {z-index: 2000000 !important;}';
				}
				JlQ('head').append('<style>.mg-input {outline:none;padding-bottom: 2px;} ' + safari + '</style>');
			}
			else if (JlQ.browser.opera) {
				JlQ('head').append('<style>.mg-box-model-container {min-width: 286px;}</style>');
			}
			else if (JlQ.browser.msie && document.documentMode < 9) {
				JlQ('head').append('<style> .mg-welcome {border: 3px solid #E79BFF !important;}</style>');
			}
		},
			
		depurateHTML = function () {

			JlQ('body script').each(function () {
				var $this = JlQ(this);
				$this.html($this.html().replace(/document.write\s*\((?:\s*([\'\"]).*?\1\s*\)|[^;]+)/g, ''));
			});
		},

		activateProps = function () {

			var $supPropTr = JlQ('.mg-panel-properties .mg-prop-trigger'),
				events = $supPropTr.data('events');

			if (!JlQ('.mg-panel-properties #mg-elproperty-position').length) {
				JlQ.each(MGDefs.properties, MGED.populateGroup);
			}
			JlQ('.mg-changeable-prop').live('click', MGED.editProperty);
			JlQ('.mg-changeable-prop, .mg-changeable-prop > input').live('hover', MGED.togglePropButtons);
			JlQ('.mg-removable-attr, .mg-removable-attr > input').live('hover', MGED.toggleAttrButtons);
			JlQ('#mg-remove-attr').live('click', MGED.removeAttribute);

			if (!JlQ('.mg-panel-filemanage').hasClass('mg-hidden')) {
				panelClose.call(JlQ('.mg-file-topmenu'));
			}
			if (!events || !events.click) {
				JlQ('.mg-panel-properties .mg-prop-trigger').click(toggleSubprop);
			}
		},
		
		deactivateProps = function () {

			JlQ('.mg-changeable-prop').die('click', MGED.editProperty);
			JlQ('.mg-changeable-prop, .mg-changeable-prop > input').die('hover', MGED.togglePropButtons);
			JlQ('.mg-removable-attr').die('hover', MGED.toggleAttrButtons);
			JlQ('#mg-remove-attr').die('click', MGED.removeAttribute);

			if (!JlQ('.mg-panel-shadow').hasClass('mg-hidden')) {
				MGED.cancelShadow();
			}
			if (!JlQ('.mg-panel-jpicker').hasClass('mg-hidden')) {
				MGED.editColorCancel();
			}
			JlQ('.mg-panel-filemanage').addClass('mg-hidden');

			unCharacterizeElement(true);

			MGD.elIsSelected = false;
		},
		
		panelEvents = {

			actionAddContruct : function () {

				JlQ('.mg-panel-properties, .mg-panel-addelement').removeClass('mg-hidden');
				
				JlQ('#mg-add-element .mg-button-radio').removeClass('mg-button-down').click(toggleAddButtons);
				JlQ('#mg-add-element .mg-newel-more').click(toggleAddOptions);
				JlQ('#mg-add-element .mg-add-removable').remove();

				if (!MGD.defDisplay) {
					MGD.populateDefDisplay();
				}
				that.bringToFront(JlQ('.mg-panel-addelement'));

				activateProps();				
			},

			actionAddDestroy : function () {

				JlQ('.mg-panel-properties, .mg-panel-addelement').addClass('mg-hidden');

				JlQ('#mg-add-element .mg-button-radio').unbind('click', toggleAddButtons);
				JlQ('#mg-add-element .mg-newel-more').unbind('click', toggleAddOptions);

				deactivateProps();
			},

			actionEditContruct : function () {

				JlQ('body').append('<div class="mg-cursors mg-nohighlight" id="mg-cursor"></div><div class="mg-cursors mg-nohighlight" id="mg-cursor-temp"></div><div id="mg-cursor-patch" class="mg-add-removable mg-nohighlight" style="display: none;"></div><div id="mg-cursor-layer" class="mg-nohighlight"></div>');
				
				JlQ('*:not(.mg-nohighlight):not(body)').live('click', that.toggleElementSelection)
					.live('mouseenter', highlightElement)
					.live('dblclick', dblClickElement);

				JlQ('*').live('mouseout', unHighlightElement);
				JlQ('#mg-cursor').live('mousemove', moveInsideElement);

				JlQ('.mg-panel').mouseenter(resetProperties);
				JlQ('body').mouseleave(resetProperties);

				if (!JlQ('#mg-selector-domtree').children().first().hasClass('mg-invisible')) {
					MGCR.syncCSS();
					JlQ('.mg-panel-domtree').removeClass('mg-hidden');
				}
				if (!MGTD.rendered) {
					MGTD.renderDOM();
				}
				JlQ('.mg-edit-panels').removeClass('mg-item-disabled');

				activateProps();

				JlQ('.mg-panel-properties').removeClass('mg-hidden');

				MGMV.toggleEditMenu();

				MGED.activateSpinner(JlQ('.mg-spinner:visible'));
			},

			actionEditDestroy : function () {

				JlQ('*:not(.mg-nohighlight):not(body)').die('click', that.toggleElementSelection)
					.die('mouseenter', highlightElement)
					.die('dblclick', dblClickElement);

				JlQ('*').die('mouseout', unHighlightElement);

				JlQ('.mg-panel').unbind('mouseenter', resetProperties);
				JlQ('body').unbind('mouseleave', resetProperties);
				
				JlQ('.mg-cursors, #mg-cursor-layer').remove();
				JlQ('#mg-cursor').die('mousemove', moveInsideElement);
				JlQ('.mg-panel-properties, .mg-panel-domtree, .mg-panel-quickedit').addClass('mg-hidden');

				JlQ('.mg-edit-panels').addClass('mg-item-disabled');

				JlQ('#mg-cursor-patch').hide();

				deactivateProps();

				MGMV.toggleEditMenu();
			}
		},
			
		highlightElement = function (el) {

			if (MGD.elIsSelected || el == null) return;

			if (typeof(el.handler) != 'undefined') {
				el.stopImmediatePropagation();
				el = this;
			}
			if (el.tagName == 'HTML') return;

			var $el = JlQ(el);

			if ($el.parents('.mg-nohighlight').length) return;

			shadowElement(el);
			that.tryCharacterizeElement();
		},

		unHighlightElement = function (ev) {

			if (MGD.elIsSelected || JlQ(this).parents('.mg-nohighlight').length || oldPageX == ev.pageX && oldPageY == ev.pageY) return;
			
			oldPageX = ev.pageX;
			oldPageY = ev.pageY;

			unShadowElement();
		},

		shadowElement = function (el) {

			var $el = JlQ(el);

			that.showElement($el, 'mg-cursor');

			MGD.lastCalled = el;
			MGD.$lastCalled = JlQ(el);
		},

		dblClickElement = function () {

			if (JlQ(this).parents('.mg-nohighlight').length || JlQ.browser.msie && JlQ(this).hasClass('JlQTextShadow')) return;

			if (!MGD.elIsSelected) {
				that.toggleElementSelection();
			}
			MGMV.dblClickCursor();
		},

		getSortedAttributes = function (el) {

			if (!el || !el.attributes) return [];

			var attr = JlQ.grep(el.attributes, function (v) {return v.name != '<';});
			
			if (!attr.length) return [];

			return JlQ.makeArray(attr).sort(function (a, b) {return a.name > b.name});
		},

		editPageMatch = function () {

			MGED.openEditarea('pageMatch', JlQ('#mg-final-page-match').val(), {
				syntax: 'php',
				save_callback: 'MGP.savePageMatch'
			});
		},

		switchMatchAll = function () {

			var $scriptVal = JlQ('#mg-match-script');
				$matchVal = JlQ('#mg-page-match-value');

			if (JlQ(this).attr('checked')) {
				syntMatch = $matchVal.html();
				scriptName = $scriptVal.val();
				matchValue = JlQ('#mg-final-page-match').val();
				if (!startMatchValue) startMatchValue = matchValue;
				$scriptVal.val('#.*#');
				that.savePageMatch(null, "if (1) {\n\treturn 'PAGE_FOUND';\n}");
				$matchVal.html('All Pages');
			}
			else {
				$scriptVal.val(scriptName);
				that.savePageMatch(null, matchValue);
				if (startMatchValue == matchValue) {
					$matchVal.html(syntMatch);
				}
			}
		},

		characterizeElement = function ($el, andFix, hiddenBehavior) {

			if (!$el.length) {
				unCharacterizeElement();
				return;
			}
			var attr,
				hasImportant = MGD.hasImportant($el),
				tag = $el[0].tagName,
				appProps = {},
				/*impProps = {},*/
				appBorder = [],
				displayValue = (hiddenBehavior == 'force'),
				noBorder, group, property, p, r, rp, i, v, appTo,
				
				dispProp = function (p, v) {
					MGED.extProperties[p] = v;
					document.getElementById('mg-elproperty-' + p).innerHTML = MGUtils.cutText(v, 30, p == 'background-image');
				};

			JlQ('#mg-current-element').text(tag);
			JlQ('#mg-current-text').text(MGUtils.cutText($el.html(), 40));

			if (!hiddenBehavior || (document.getElementById('mg-elprop-attr').style.display != 'none') != displayValue) {
				JlQ('#mg-elprop-attr').empty();

				attr = getSortedAttributes($el[0]);

				if (attr.length) {
					JlQ.each(attr, function (i, attr) {
						JlQ('#mg-elprop-attr').append('<div class="mg-changeable-prop mg-removable-attr"><span><b>'+attr.name+'</b> : </span><span class="mg-changeable-input" id="mg-elattr-'+attr.name+'">'+MGUtils.cutText(attr.value, 30)+'</span></div>');
						//JlQ('#mg-elattr-'+attr.name).parent().data('rval', attr.value);
						MGED.extAttributes[attr.name] = attr.value;
					});
				}
				else {
					JlQ('#mg-elprop-attr').text('None');
				}
			}
			if (JlQ.browser.msie && document.documentMode < 9) {
				MGDefs.shProps['text-shadow'] = 1;
			}
			for (group in MGDefs.properties) {
				
				//groupEl = document.getElementById('mg-elprop-' + group);
				if (hiddenBehavior && propShown[group] == displayValue) continue;

				property = MGDefs.properties[group];

				for (i = 0; p = property[i]; i++) {
					
					if (MGDefs.shProps[p]) continue;

					if (that.currentMode == 'Add' && p == 'display' && that.currentAddB) {
						v = MGD.defDisplay[that.currentAddB.attr('id')];
					}
					else {
						v = $el.css(p);
					}
					if (appTo = MGDefs.shPropsInv[p]) {
						if (!appProps[appTo]) {
							appProps[appTo] = [];
						}
						appProps[appTo].push(v);
					}
					if (hasImportant && $el.cssImportant(p)) {
						/*
						if (appTo) {
							impProps[p] = 1;
						}
						else {
						*/
							v = v + ' !important';
						//}
					}
					dispProp(p, v);
				}
			}
			if (JlQ.browser.msie && document.documentMode < 9) {
				delete MGDefs.shProps['text-shadow'];
			}
			for (p in appProps) {
				rp = MGED.reduceProp(p, appProps[p]);
				if (MGDefs.dimensionedProps[p] == 2 && !noBorder) {
					if (!(noBorder = (rp.length > 1))) {
						appBorder.push(rp[0]);
					}
				}
				r = rp.join(' ');
				/*
				if (impProps[p]) {
					r += ' !important'
				}
				*/
				dispProp(p, r);
			}
			if (noBorder === false) {
				dispProp('border', appBorder.join(' '));
			}

			if (andFix) {
				MGED.fixProps();
			}
		},

		moveInsideElement = function (ev) {

			var noScroll = JlQ.browser.msie && document.documentMode >= 9 && JlQ(this).width() == 0,
				calling;

			JlQ('#mg-cursor').css('display', 'none');
			calling = JlQ.elementUnder(ev.pageX, ev.pageY, noScroll);
			JlQ('#mg-cursor').css('display', 'block');
			highlightElement(calling);
		},

		toggleSubprop = function (ev) {

			var $this = JlQ(this),
				ancId = $this.siblings('.mg-changeable-input').attr('id'),
				$els2Toggle, prop, isExpanded;

			if (!ancId) return;

			prop = ancId.replace(/^mg-elproperty-/, '');
			isExpanded = $this.hasClass('mg-prop-collapse');
			$els2Toggle = JlQ('.mg-panel-properties .mg-changeable-prop[proppar='+prop+']');
			if (isExpanded && $els2Toggle.children('.mg-prop-collapse').length) {
				$els2Toggle.children('.mg-prop-collapse').click();
			}
			$els2Toggle.toggleClass('mg-hidden', isExpanded);
			$this.toggleClass('mg-prop-expand mg-prop-collapse');
			
			ev.stopPropagation();
			ev.stopImmediatePropagation();
		},

		toggleView = function () {

			var $this = JlQ(this),
				$a = $this.children('a'),
				item = $a.attr('item'),
				$panel = JlQ('.mg-panel-' + item),
				scrollBottom;

			if ($this.hasClass('mg-item-disabled')) return;

			if (item == 'domtree' && $panel.hasClass('mg-hidden')) {
				MGCR.syncCSS();
			}
			if (item == 'transform-chain' && $panel.hasClass('mg-hidden')) {
				MGTut.nextStep('undoRedo');
				scrollBottom = true;
			}
			$panel.toggleClass('mg-hidden');
			that.bringToFront($panel);
			$a.prev().toggleClass('mg-invisible');
			if (scrollBottom) {
				JlQ('.mg-transform-chain').scrollTop(JlQ('.mg-transform-table').height());
			}
		},

		panelClose = function () {

			var ritem,
				$this = JlQ(this),
				panel = $this.closest('.mg-panel');
			
			if (panel.hasClass('mg-panel-filemanage') && !JlQ('#mg-file-publish').hasClass('mg-hidden')) {
				MGD.newTransform();
			}
			else if (panel.hasClass('mg-panel-quickedit')) {
				MGMV.cancelQuickEdit();
			}
			else if (panel.hasClass('mg-panel-jpicker')) {
				MGED.editColorCancel();
				return;
			}
			panel.addClass('mg-hidden');

			if (ritem = $this.attr('ritem')) {
				JlQ('a[item='+ritem+']').prev().addClass('mg-invisible');
			}
		},

		startDragPanels = function () {
			
			that.bringToFront(JlQ(this));
			
			JlQ('.mg-panel-addchoices').remove();

			MGED.closeAutocomplete();
		},

		keepElementUpdated = function () {

			var newEl, candEl = that.currentAddB.children().first();

			if (candEl.hasClass('mg-to-remove')) {
				candEl = candEl.find(':not(.mg-to-remove)').first();
			}
			newEl = candEl.clone().removeClass('mg-hidden mg-added-absolute-element');

			if (newEl.length) {
				MGD.updateLastCalled(newEl);
				that.updateElData();
				if (typeof(newEl[0]) == 'object' && newEl[0].tagName) {
					JlQ('#mg-edit-elem').toggleClass('mg-hidden', !!JlQ.autoCloseTags[newEl.get(0).tagName.toLowerCase()]);
				}
			}
			else {
				unCharacterizeElement();
			}
			JlQ('.mg-panel-addchoices').remove();
		},

		closeAddOptions = function () {

			JlQ('.mg-panel-addchoices').remove();
			JlQ('body').unbind('click', that.closeAddOptions);
		},

		toggleMainButtons = function () {

			var oldDestroyCallback,
				newMode = JlQ(this).attr('mode'),
				newContructCallback;

			JlQ(this).siblings('.mg-button-down').toggleClass('mg-button-down');
			JlQ(this).toggleClass('mg-button-down').removeAttr('style');
			if (!JlQ('#mg-main-action > .mg-button-down').length) {
				JlQ('#mg-main-action > span[mode!='+newMode+']').first().toggleClass('mg-button-down');
			}
			newMode = JlQ('#mg-main-action > .mg-button-down').attr('mode');
			oldDestroyCallback = 'action' + that.currentMode + 'Destroy';
			newContructCallback = 'action' + newMode + 'Contruct';

			if (typeof(panelEvents[oldDestroyCallback]) != 'undefined') {
				panelEvents[oldDestroyCallback]();
			}
			if (typeof(panelEvents[newContructCallback]) != 'undefined') {
				panelEvents[newContructCallback]();
			}
			that.currentMode = newMode;

			that.setStatus('ready');
		},

		toggleAddButtons = function () {

			var $this = JlQ(this),
				newId = $this.attr('id');

			if ($this.hasClass('mg-button-down')) return;

			JlQ('.mg-button-down', $this.closest('.mg-panel')).toggleClass('mg-button-down');
			$this.toggleClass('mg-button-down').removeAttr('style');
			if (!JlQ('.mg-button-down').length) {
				JlQ('#mg-add-element div.mg-newel-cont[id!='+newId+']').first().toggleClass('mg-button-down');
			}
			that.currentAddB = JlQ('#mg-add-element .mg-button-down');
			
			keepElementUpdated();

			MGED.enableQuickProps();

			JlQ('.mg-panel-addchoices').remove();
/*
			if (newId == 'mg-add-img') {
				JlQ('#mg-elprop-attr').removeClass('mg-hidden').show();
				that.bringToFront(JlQ('.mg-panel-properties'));
				JlQ('.mg-panel-properties .mg-subpanel').scrollTop(0);
				if (!JlQ('#mg-add-img-info').length) {
					JlQ('#mg-elprop-attr > .mg-changeable-prop:has(#mg-elattr-src)').append('<div id="mg-add-img-info" class="mg-prop-msg"><span class="ui-corner-all">Click here to add an image.</span></div>');
					JlQ('#mg-add-img-info').delay(5000).fadeOut(1000, function () {
						JlQ(this).remove();
					});
				}
			}
*/
			MGD.trsfRemoveNew();
		},

		toggleAddOptions = function (ev) {

			if (JlQ('.mg-panel-addchoices').length) {
				JlQ('.mg-panel-addchoices').remove();
			}

			var $this = JlQ(this),
				$choices = $this.parent().clone(),
				css = MGUtils.getWindowPosition($this, {top: 5, left: $this.width()});
			
			ev.stopPropagation();

			$choices.addClass('mg-panel mg-panel-addchoices')
				.removeClass('mg-newel-button-cont')
				.css(css)
				.children('span').remove();
			
			JlQ('.mg-newel-cont', $choices).removeClass('mg-hidden mg-button-down')
				.hover(MGBP.hoverButtons)
				.click(chooseAddButton)
				.draggable('destroy');

			JlQ('.mg-add-removable', $choices).remove();
			
			that.bringToFront($choices);

			JlQ('body').append($choices).click(MGP.closeAddOptions);
		},

		shrinkMenu = function () {

			while (JlQ('.mg-mainmenu > li:last-child').position().top) {
				JlQ('.mg-panel-main').width(JlQ('.mg-panel-main').width() + 5);
			}
			JlQ('#mg-update-main').css('width', 'auto');
			JlQ('#mg-menu-more').remove();
		},

		toggleMainMore = function () {

			if (JlQ('.mg-mainmenu > li:last-child').position().top) {
				if (!JlQ('#mg-menu-more').length) {
					JlQ('<div id="mg-menu-more" class="mg-menu-clickable"><span></span></div>')
						.click(shrinkMenu)
						.appendTo(JlQ('.mg-panel-main .mg-subpanel-group'));
				}
			}
			else {
				JlQ('#mg-menu-more').remove();
			}
		},

		tryFixProperties = function () {

			if (changingCursor) {
				setTimeout(tryFixProperties, cursorDelay);
			}
			else {
				MGED.fixProperties();
			}
		},

		chooseAddButton = function () {

			var $orig = JlQ('#mg-add-element #' + this.id);

			$orig.siblings('div').addClass('mg-hidden');
			$orig.removeClass('mg-hidden').click();
			JlQ('.mg-panel-addchoices').remove();
		},

		resetProperties = function () {
		
			if (MGD.elIsSelected || JlQ(this).parents('.mg-nohighlight').length) return;

			unCharacterizeElement();
		},

		unCharacterizeElement = function (andCancel) {
		
			if (andCancel) {
				if (JlQ('.mg-property-input').length) {
					MGED.cancelProperty();
				}
				MGED.disableQuickProps();
			}
			JlQ('#mg-current-element').empty();
			JlQ('#mg-current-text').empty();
			JlQ('#mg-elprop-attr').empty();
			MGED.setEmptyTypespec();
			JlQ('.mg-panel-properties .mg-changeable-input').empty().attr('mgtitle', '');
			JlQ('.mg-elem-actions').addClass('mg-hidden');
		},

		unShadowElement = function () {

			MGD.lastCalled = null;
			MGD.$lastCalled = null;

			JlQ('#mg-cursor').css({
				width: 0,
				height: 0
			});
		},
			
		moveTitles = function (ev) {

			var $baloon = JlQ('#mg-baloon'),
				css = {},
				winDim = getWindowDim(),
				right, bottom;
			
			if (!$baloon.length) return;

			if ($baloon.css('left') != 'auto') {
				css.left = ev.clientX + that.balOff.left;
			}
			else {
				right = true;
			}
			if ($baloon.css('top') != 'auto') {
				css.top = ev.clientY + that.balOff.top;
			}
			else {
				bottom = true;
			}
			if ($baloon.width() > 400) {
				css.whiteSpace = 'normal';
			}
			$baloon.css(css);

			if (right || $baloon.offset().left - $window.scrollLeft() + $baloon.outerWidth() > winDim.width) {
				$baloon.css({left: 'auto', right: winDim.width - ev.clientX + that.balOff.left});
			}
			if (bottom || $baloon.offset().top - $window.scrollTop() + $baloon.outerHeight() > winDim.height) {
				$baloon.css({top: 'auto', bottom: winDim.height - ev.clientY + that.balOff.top});
			}
		},
			
		showTitles = function (ev) {

			var $baloon = JlQ('#mg-baloon'),
				$this = JlQ(this),
				pos = {top: ev.clientY + that.balOff.top, left:  ev.clientX + that.balOff.left},
				val;

			if (ev.type == 'mouseover') {
				val = $this.attr('mgtitle');
				if ($this.attr('id') == 'mg-qp-background-image' && val.search(/^\s*url\s*\(/) != -1) {
					val = MGUtils.redimImage(val, {width: 15, height: 15}, {width: 150, height: 150});
				}
				if ($baloon.length) {
					$baloon.html(val);
				}
				else {
					JlQ('<div id="mg-baloon" class="mg-baloon mg-nohighlight">' + val + '</div>').appendTo('body');
				}
				JlQ('#mg-baloon').css(pos);

				if (ev && ev.target) {
					$this.mousemove(moveTitles);
				}
			}
			else {
				$baloon.remove();
				$this.unbind('mousemove', moveTitles);
			}
		},
			
		recallerHover = function (ev) {
			
			if (ev.type == 'mouseenter') {
				JlQ(this).clearQueue().stop().css('opacity', '1');
			}
			else {
				JlQ(this).fadeTo(1000, 0);
			}
		},

		jlMinimized = function () {
			
			JlQ('.mg-panel-main').addClass('mg-toggled');
			JlQ('.mg-recaller').delay(3000).fadeTo(1000, 0);
		};


	that.maxZIndex = 1000014;
	that.currentMode = 'Nav';
	that.currentAddB = null;
	that.clickingCursor = false;

	that.balOff = {top: 12, left: 18};

	that.loading = false;


	that.getpropShown = function ($panel) {
		
		var $advPanel = JlQ('.mg-elprop-advanced', $panel);

		if (!$advPanel.length) return true;

		return propShown[$advPanel.attr('id').replace(/^mg-elprop-/, '')];
	};

	that.updatePropShown = function ($tgt, val) {

		if ($tgt.attr('id') == 'mg-elprop-attr') return;
		
		var $advPanel = $tgt.hasClass('mg-elprop-advanced') ? $tgt : JlQ('.mg-elprop-advanced', $tgt),
			prop = $advPanel.attr('id').replace(/^mg-elprop-/, '');

		propShown[prop] = (typeof(val) == 'undefined') ? !$advPanel.is(':visible') : val;

		if (prop == 'boxmodel') {
			MGED.activateBoxModel();
		}
	};

	that.fixPosFix = function ($panel) {

		if (JlQ.browser.mozilla4 || JlQ.browser.msie || JlQ.browser.opera) {
			$panel.cssImportant('position', 'fixed');
		}
	};

	that.bringToFront = function ($el) {

		if (typeof($el.originalEvent) != 'undefined') {
			$el = JlQ(this);
		}
		if ($el.hasClass('mg-panel-main')) return;

		$el.css('z-index', ++that.maxZIndex);
	};

	that.showElement = function ($el, id) {

		var offset = $el.offset(),
			winDim = getWindowDim(),
			w = $el.outerWidth(),
			h = $el.outerHeight();

		if (w >= winDim.width -5) {
			w = winDim.width -5;
		}
		if (h >= winDim.height -5) {
			h = winDim.height -5;
		}

		JlQ('#' +id).css({
			opacity: 0.3,
			left: offset.left,
			top: offset.top,
			width: w,
			height: h
		});
	};

	that.tryCharacterizeElement = function () {

		if (MGD.lastCalled && oldLastCalled == MGD.lastCalled) {
			characterizeElement(MGD.$lastCalled, false, true);
			changingCursor = 0;
		}
		else {
			if (changingCursor) {
				clearTimeout(changingCursor);
			}
			oldLastCalled = MGD.lastCalled;
			changingCursor = setTimeout(MGP.tryCharacterizeElement, cursorDelay);
		}
	};

	that.toggleAll = function () {

		if (JlQ('.mg-panel-main').hasClass('mg-toggled')) {
			JlQ('.mg-recaller').remove();
			JlQ('.mg-nohighlight').removeClass('mg-toggled');
		}
		else {
			JlQ('.mg-nohighlight:not(.mg-panel-main)').addClass('mg-toggled');
			JlQ('<div class="mg-panel mg-button mg-recaller mg-nohighlight">Show Jelliphy</div>')
				.click(that.toggleAll)
				.hover(recallerHover)
				.appendTo('body');
			JlQ('.mg-panel-main').effect('transfer', {to: '.mg-recaller', className: 'mg-recaller-shadow'}, 500, jlMinimized);
		}
	};

	that.toggleElementSelection = function (ev) {

		if (JlQ.browser.msie && document.documentMode >= 9 && ev && ev.liveFired && 
			(ev.liveFired.activeElement && (ev.liveFired.activeElement.nodeName == 'BODY' || ev.liveFired.activeElement.id == 'frame_mg-editarea')
			|| !this.parentNode && this.nodeName != 'BODY')
		) return;

		that.clickingCursor = true;

		var $this = JlQ(this),
			senderPage = !$this.parents('.mg-domelem').length && !$this.hasClass('mg-domelem'),
			tmpTextShown;

		if (JlQ.browser.msie && MGD.$lastCalled && MGD.$lastCalled.hasClass('JlQTextShadow')) {
			tmpTextShown = propShown.text;
			propShown.text = false;
			shadowElement(MGD.lastCalled.parentNode);
			that.toggleElementSelection(JlQ.extend(ev, {liveFired : null}));
			propShown.text = tmpTextShown;
			return;
		}
		if ($this.parents('.mg-nohighlight, .jPicker').length && senderPage || $this.hasClass('mg-images')) {
			that.clickingCursor = false;
			return;
		}
		if (ev) {
			if (ev.timeStamp - clickTime < dblClickDelay) {
				return;
		/*
				MGMV.dblClickCursor();
				if (MGD.elIsSelected) {
					return;
				}
		*/
			}
			clickTime = ev.timeStamp;
		}
		if (senderPage)	{
			MGTD.renderDOM(MGD.elIsSelected ? null : MGD.$lastCalled);
		}
		else {
			MGTD.selectDOM($this, true);
		}
		MGD.elIsSelected = !MGD.elIsSelected;

		if (MGD.elIsSelected) {
			if (MGD.lastCalled == null) {
				MGD.elIsSelected = false;
				that.clickingCursor = false;
				return;
			}
			tryFixProperties();
			MGMV.enrichCursor();
			setTimeout(function () {
				MGD.updateAESelector();
				that.clickingCursor = false;
			}, dblClickDelay);
		}
		else {
			MGMV.pauperizeCursor();
		
			unCharacterizeElement(true);

			if (JlQ('#mg-element-text').length) {
				MGED.restoreText();
			}
			JlQ('#mg-element-selector').html('<option>none</option>');
			if (!JlQ.browser.opera) {
				JlQ('.mg-panel-advanced-edit').css('width', JlQ('.mg-panel-advanced-edit').css('min-width'));
			}
			JlQ('.mg-panel-jpicker, .mg-panel-filemanage').addClass('mg-hidden');

			if (!JlQ('.mg-panel-shadow').hasClass('mg-hidden')) {
				MGED.cancelShadow();
			}
			if (!JlQ('.mg-panel-editarea').hasClass('mg-hidden')) {
				MGED.closeEditarea();
			}
			that.clickingCursor = false;
		}
		if (!JlQ('.mg-panel-advanced-edit').hasClass('mg-hidden')) {
			that.bringToFront(JlQ('.mg-panel-advanced-edit'));
		}
		if (!JlQ('#mg-quickedit').hasClass('mg-hidden')) {
			MGMV.cancelQuickEdit();
		}
		if (JlQ('#mg-cursor').hasClass('mg-editph')) {
			MGMV.cancelEditElement();
		}
		else {
			MGMV.toggleEditMenu();
		}
	};

	that.clickCursorPanel = function (ev) {

		if (ev.timeStamp - clickTime < dblClickDelay) {
			MGMV.dblClickCursor();
		}
	};

	that.updateElData = function (andQuickProps) {

		if (!JlQ.browser.mozilla && !JlQ.browser.msie) {
			JlQ('head > div.mg-norender').html("");
			MGD.$lastCalled.appendTo('head > div.mg-norender');
		}
		MGD.defDisplay[that.currentAddB.attr('id')] = MGD.$lastCalled.css('display');
		characterizeElement(MGD.$lastCalled, true);

		if (andQuickProps) {
			MGED.updateQuickProps();
		}
		MGMV.initDragDrop(that.currentAddB);
	};

	that.savePageMatch = function (id, value) {

		JlQ('#mg-final-page-match').val(value);
		JlQ('#mg-page-match-value').text(MGUtils.cutText(value, 70));
		if (id) {
			MGED.closeEditarea();
		}
	};

	that.setStatus = function (status) {

		if (mainStatus != status) {
			JlQ('#mg-cur-status').html(MGLang.common['status_' + status]);
			mainStatus == status;
		}
	};

	that.initPanels = function () {
		
		JlQ('.mg-panel').mousedown(that.bringToFront)
			.draggable({ 
				cancel: '.mg-subpanel, .mg-subpanel-element, #mg-inline-jpicker, textarea',
				start: startDragPanels,
				cursor: 'move'
			});
		if (JlQ.browser.webkit) {
			JlQ('.mg-panel').each(function () {
				this.onselectstart = function () { return false; };
			});
		}
		JlQ('.mg-panel-main').resizable({
			alsoResize: '#mg-update-main',
			minHeight: 90,
			minWidth: 223,
			maxHeight: 160,
			maxWidth: 350,
			resize: toggleMainMore
		});
		JlQ('.mg-panel-properties').resizable({
			alsoResize: '.mg-subpanel',
			minHeight: 82, 
			minWidth: 191
		});
		JlQ('.mg-panel-editarea').resizable({
			alsoResize: '#frame_mg-editarea,#mg-editarea,#mg-editarea-container', 
			minHeight: 40, 
			minWidth: 191,
			stop: JlQ.browser.msie || JlQ.browser.webkit ? function () {
				JlQ('#reset_highlight', JlQ('#frame_mg-editarea').contents().get(0)).click();
			} : null
		});

		toggleMainMore();
	};

	that.initButtons = function () {

		JlQ('.mg-button-mode').click(toggleMainButtons);
		JlQ('.mg-menu-item-view li').click(toggleView);

		JlQ('.mg-transform-table tr:has(td)').live('hover', MGD.highlightTransform);

		JlQ('#mg-page-match-value').click(editPageMatch);
		JlQ('#mg-page-match-all').click(switchMatchAll);

		JlQ('.mg-generic-cancel').click(panelClose);
	};

	that.initOthers = function () {

		if (!JlQ.browser.msie) {
			JlQ('ul.mg-mainmenu > li > ul').css("opacity","0.95");
		}
		JlQ('ul.mg-mainmenu').superfish({
			speed: 0,
			delay: 300
		});

		if (JlQ.browser.webkit && navigator.userAgent.toLowerCase().indexOf('chrome') != -1) {
			JlQ.browser.safari = false;
		}
		if (JlQ.browser.mozilla) {
			JlQ.browser[parseInt(JlQ.browser.version) < 2 ? 'mozilla3' : 'mozilla4'] = true;
		}
		JlQ(window).add(JlQ('.mg-subpanel')).scroll(MGED.closeAutocomplete);

		if(document.addEventListener) document.addEventListener('keydown', that.consoleMan, false);
		else if(document.attachEvent) document.attachEvent('onkeydown', that.consoleMan);
		else document['onkeydown'] = that.consoleMan;

		JlQ('*[mgtitle]').live('hover', showTitles);
            
	};

	that.consoleMan = function (ev) {

		ev = ev || window.event;
		
		var keyCode = ev.keyCode || ev.which,
			key = String.fromCharCode(keyCode),
			$sender = JlQ(ev.explicitOriginalTarget || ev.originalTarget || ev.srcElement),
			caught;

		if (keyCode == 17 || !key || $sender.is('.mg-input, .mg-textarea') || $sender.parents('.mg-panel').length) return;

		if (keyCode == 46) {
			if (!JlQ('#mg-menu-delete').hasClass('mg-item-disabled')) {
				JlQ('#mg-menu-delete').click();
				caught = true;
			}
		}
		else if (ev.ctrlKey) {
			if (ev.shiftKey) {
				switch (key) {
					case 'V':
						if (!JlQ('#mg-menu-paste-replace').hasClass('mg-item-disabled')) {
							JlQ('#mg-menu-paste-replace').click();
							caught = true;
						}
						break;
				}
			}
			else {
				switch (key) {
					case 'Z':
						MGD.trsfUndo();
//						caught = true;
						break;
					case 'Y':
						MGD.trsfRedo();
//						caught = true;
						break;
					case 'X':
						if (!JlQ('#mg-menu-cut').hasClass('mg-item-disabled')) {
							JlQ('#mg-menu-cut').click();
							caught = true;
						}
						break;
					case 'C':
						if (!JlQ('#mg-menu-copy').hasClass('mg-item-disabled')) {
							JlQ('#mg-menu-copy').click();
							caught = true;
						}
						break;
					case 'V':
						if (!JlQ('#mg-menu-paste-after').hasClass('mg-item-disabled')) {
							JlQ('#mg-menu-paste-after').click();
							caught = true;
						}
						break;
					case 'I':
						if (!JlQ('#mg-menu-paste-inside').hasClass('mg-item-disabled')) {
							JlQ('#mg-menu-paste-inside').click();
							caught = true;
						}
						break;
					case 'B':
						if (!JlQ('#mg-menu-paste-before').hasClass('mg-item-disabled')) {
							JlQ('#mg-menu-paste-before').click();
							caught = true;
						}
						break;
					case 'M':
						that.toggleAll();
						caught = true;
						break;
				}
			}
		}
		if (caught) {
				ev.cancelBubble = true;
				ev.returnValue = false;
				if (ev.stopPropagation) {
					ev.stopPropagation();
					ev.preventDefault();
				}
				return false;
		}
	};

	that.onlineFeatOnly = function (ev) {
		
		if (!ev) return;

		ev.stopPropagation();
		ev.preventDefault();
		
		MGDial.warning(MGLang.warnings.full_only_feature + MGLang.warnings.full_only, {type: 'info'});
	};



	that.init = function (op) {
		
		that.loading = true;

		var i, s, evl, p = 'JlQ,JlQ.ui,JlQ.preloadImages,MGBP,MGDefs,MGF,MGD,MGED,MGTD,MGMV,MGCR,MGOP,MGLang,EAL'.split(',');
		for (i = 0; s = p[i]; i++) {
			evl = eval('typeof ' + s);
			if (evl == 'undefined') {
				that.loading = false;
				return -1;
			}
		}
		setTimeout('EAL.prototype.window_loaded()', 500);


		$window = JlQ(window);



		if (JlQ.browser.msie && document.documentMode < 8) {
			alert(MGLang.warnings.ie_version_incompatible);
			JlQ('.mg-panel').remove();
			that.loading = false;

			return;
		}
		
		if (!JlQ.browser.msie) {
			depurateHTML();
		}
		
		JlQ.preloadImages([
			MGF.MGRoute + "online/jelliphy/custom/mg/images/jlphcomp.png",
			MGAddPath + "custom/mg/images/repeatbg.png",
			MGF.MGRoute + "online/jelliphy/custom/mg/css/images/JLui-icons_0a0a0a_256x240.png"
		]);
		MGF.init();

		that.initPanels();
		MGBP.initBasicPanels();

		MGBP.initBasicButtons();
		that.initButtons();
		
		that.initOthers();

		JlQ.each('MGDefs,MGD,MGTD,MGMV,MGCR,MGOP,MGED,MGTut'.split(','), function () {
			eval(this + '.init()');
		});

		JlQ('<div style="position:absolute;left:0;top:0;bottom:0;right:0;"></div>').css('opacity', '0')
			.click(that.onlineFeatOnly)
			.appendTo('.mg-subpanel-page-match');



		adaptStyle();

		if (!JlQ.browser.mozilla && !JlQ.browser.msie) {
			JlQ('head').append('<div class="mg-norender"></div>');
		}

		if (MGOP.prefs.no_tutorial != 'true' && op != 'noTut') {
			MGTut.startTutorial();
		}

		JlQ('span[mode=Nav]').unbind('click').click(that.onlineFeatOnly);

		that.loading = false;
		return 0;

	};


	that.characterizeElement = characterizeElement;
	that.closeAddOptions = closeAddOptions;
	that.panelClose = panelClose;
	that.highlightElement = highlightElement;
	that.shadowElement = shadowElement;
	that.showTitles = showTitles;
}

